import { getEnv } from "./env";
import { go } from "./wxAPI";
const formatTime = (date) => {
  const year = new Date(date).getFullYear();
  const month = new Date(date).getMonth() + 1;
  const day = new Date(date).getDate();
  const hour = new Date(date).getHours();
  const minute = new Date(date).getMinutes();
  const second = new Date(date).getSeconds();

  return `${[year, month, day].map(formatNumber).join("-")} ${[hour, minute]
    .map(formatNumber)
    .join(":")}`;
};
export const formatDate = (date) => {
  const year = new Date(date).getFullYear();
  const month = new Date(date).getMonth() + 1;
  const day = new Date(date).getDate();
  let data;
  return (data = {
    dateValue: `${[year, month, day].map(formatNumber).join("-")}`,
    dateTitle: `${year}年${month}月${day}日`,
  });
};
const formatNumber = (n) => {
  n = n.toString();
  return n[1] ? n : `0${n}`;
};

const setdata = (that, key, value) => {
  that.setData({
    [key]: value,
  });
};

const filertext = (text) => {
  return text
    .replace(/{/g, "")
    .replace(/}/, "")
    .replace(/"/g, "")
    .replace(/:/g, "");
};

const formatRichText = (html) => {
  let newContent = html.replace(/<img[^>]*>/gi, function (match, capture) {
    match = match.replace(/style="[^"]+"/gi, "").replace(/style='[^']+'/gi, "");
    match = match.replace(/width="[^"]+"/gi, "").replace(/width='[^']+'/gi, "");
    match = match
      .replace(/height="[^"]+"/gi, "")
      .replace(/height='[^']+'/gi, "");
    return match;
  });
  newContent = newContent.replace(/style="[^"]+"/gi, function (match, capture) {
    match = match
      .replace(/width:[^;]+;/gi, "max-width:100%;")
      .replace(/width:[^;]+;/gi, "max-width:100%;");
    return match;
  });
  newContent = newContent.replace(/<br[^>]*\/>/gi, "");
  newContent = newContent.replace(
    /\<img/gi,
    '<img style="max-width:100%;height:auto;display:block;margin-top:0;margin-bottom:0;"'
  );
  return newContent;
};

const date = () => {
  const year = new Date().getFullYear();
  const month = new Date().getMonth() + 1;
  const day = new Date().getDate();
  return (
    year +
    "-" +
    String(month).padStart("2", 0) +
    "-" +
    String(day).padStart("2", 0)
  );
};

const ages = (str) => {
  var r = str.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/);
  if (r == null) return false;
  var birth = new Date(r[1], r[3] - 1, r[4]);
  if (
    birth.getFullYear() == r[1] &&
    birth.getMonth() + 1 == r[3] &&
    birth.getDate() == r[4]
  ) {
    var today = new Date();
    var age = today.getFullYear() - r[1];

    if (today.getMonth() > birth.getMonth()) {
      return age;
    }
    if (today.getMonth() == birth.getMonth()) {
      if (today.getDate() >= birth.getDate()) {
        return age;
      } else {
        return age - 1;
      }
    }
    if (today.getMonth() < birth.getMonth()) {
      return age - 1;
    }
  }
  return "输入的日期格式错误！";
};

const tofixed2 = (val) => {
  let value = val;
  value = value.replace(/[^\d.]/g, ""); //清除"数字"和"."以外的字符
  value = value.replace(/^\./g, ""); //验证第一个字符是数字而不是字符
  value = value.replace(/\.{2,}/g, "."); //只保留第一个.清除多余的
  value = value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
  value = value.replace(/^(\-)*(\d+)\.(\d\d).*$/, "$1$2.$3"); //只能输入两个小数
  return value;
};

const dateDiff = (first, second) => {
  const firstDate = new Date(first);
  const secondDate = new Date(second);
  const diff = Math.abs(firstDate.getTime() - secondDate.getTime());
  const result = parseInt(diff / (1000 * 60 * 60 * 24));
  return result ? result + 1 : 0;
};

const banneronClick = (item) => {
  //兼容辉哥的轮播事件
  item.params = item.params ? JSON.parse(item.params) : {};
  if (item.targetType == 2) {
    //1导向内容 2导向链接
    item.target = JSON.parse(item.target);
    uni.setStorageSync("weburl", item.target.weburl);
    go("/pages/weburl/weburl");
  }
  // if (item.targetType == 2) { //导向小程序
  // 	item.target = JSON.parse(item.target)
  // 	uni.navigateToMiniProgram({
  // 		appId: item.target.appId,
  // 		path: item.target.miniappurl
  // 	});
  // }
  if (item.targetType == 4) {
    //导向内部链接
    item.target = JSON.parse(item.target);
    let tabbar = [
      "/pages/index/index",
      "/pages/cate/cate",
      "/pages/car/car",
      "/pages/my/my",
    ];
    if (tabbar.includes(item.target.url)) {
      uni.switchTab({
        url: item.target.url,
      });
    } else {
      go(item.target.url + (item.target.value ? item.target.value : ""));
    }
  }
  // if (item.targetType == 5) { //导向视频号
  //   item.target = item.target.split(',');
  //   wx.openChannelsActivity({
  //     finderUserName: item.target[0],
  //     feedId: item.target[1],
  //     fail(err) {
  //       console.log(err)
  //       msg('参数有误')
  //     }
  //   });
  // }
  // if (item.targetType == 6) { //导向视频号直播
  //   wx.openChannelsLive({
  //     finderUserName: item.target,
  //     fail(err) {
  //       console.log(err)
  //       msg('参数有误')
  //     }
  //   });
  // }
};

const wan = (num) => {
  num = Number(num);
  if (num == 0) {
    return num + "";
  } else if (num > 1 && num < 10000) {
    return num + "";
  } else {
    return (num / 10000).toFixed(2) + "万";
  }
};

const plusXing = (str, frontLen, endLen, cha) => {
  let len = str.length - frontLen - endLen;
  let xing = "";
  for (let i = 0; i < len; i++) {
    xing += cha;
  }
  return str.substring(0, frontLen) + xing + str.substring(str.length - endLen);
};

const pricefitiler = (str, num) => {
  let str1 = str.substring(0, str.indexOf("-"));
  let str2 = str.substring(str.indexOf("-") + 1, str.length);
  return num == 1 ? str1 : str2;
};

const getMonthDay = (ymd) => {
  //获取这个月有多少天 数据返回 当月全日期和星期和是否是今天01
  let dangyear = new Date().getFullYear();
  let dangmonth = String(new Date().getMonth() + 1).padStart("2", 0);
  // let dangdate = String(new Date().getDate()).padStart('2', 0)
  let year = new Date(ymd).getFullYear();
  let month = String(new Date(ymd).getMonth() + 1).padStart("2", 0);
  let date = String(new Date(ymd).getDate()).padStart("2", 0);
  let days = new Date(year, month, 0).getDate();
  let daysarr = [];
  for (let i = 0; i < days; i++) {
    daysarr.push({
      date: `${year}-${month}-${String(i + 1).padStart("2", 0)}`,
      week: new Date(year, month - 1, i + 1).getDay(),
      isToday:
        dangyear == year &&
        dangmonth == month &&
        String(i + 1).padStart("2", 0) == date
          ? 1
          : 0,
    });
  }
  return daysarr;
};

//获取当月最后一天的日期
const getLastDay = (year, month) => {
  var y = new Date(`${year}-${month}-01`).getFullYear(); //获取年份
  var m = new Date(`${year}-${month}-01`).getMonth() + 1; //获取月份
  var d = new Date(y, m, 0).getDate(); //获取当月最后一日
  m = m < 10 ? "0" + m : m; //月份补 0
  d = d < 10 ? "0" + d : d; //日数补 0

  return [y, m, d].join("-");
};

const gominiapp = (appId, path) => {
  wx.navigateToMiniProgram({
    appId,
    path,
  });
};

const checkTax = (obj) => {
  if (/^[A-Z0-9]{15}$|^[A-Z0-9]{17}$|^[A-Z0-9]{18}$|^[A-Z0-9]{20}$/.test(obj)) {
    return true;
  }
};

/*获取最近4天**/
const getNext4Days = () => {
  const today = new Date();
  const days = [];

  for (let i = 1; i <= 4; i++) {
    days.push(
      new Date(today.getFullYear(), today.getMonth(), today.getDate() + i)
    );
  }

  const result = days.map((day) => day.toISOString().slice(0, 10));
  return result;
};

// module.exports = {
//   formatTime,
//   setdata,
//   filertext,
//   formatRichText,
//   date,
//   ages,
//   tofixed2,
//   dateDiff,
//   banneronClick,
//   wan,
//   plusXing,
//   pricefitiler,
//   getMonthDay,
//   getLastDay,
//   gominiapp,
//   checkTax,
//   getNext4Days,
// };

// 获取本月的开始时间
export const getStartOfMonth = () => {
  const now = new Date();
  return formatDate(new Date(now.getFullYear(), now.getMonth(), 1));
};

// 获取本月的结束时间
export const getEndOfMonth = () => {
  const now = new Date();
  const nextMonth = now.getMonth() + 1;
  const nextMonthStart = new Date(now.getFullYear(), nextMonth, 1);
  return formatDate(new Date(nextMonthStart - 1)); // 1毫秒前的时间即为本月的最后一刻
};

// 使用示例
// const startOfMonth = getStartOfMonth();
// const endOfMonth = getEndOfMonth();

// console.log('本月开始时间:', startOfMonth);
// console.log('本月结束时间:', endOfMonth);

export const getThisWeekDates = () => {
  const now = new Date();
  const currentDay = now.getDay(); // 获取当前是周几（0-6，0代表周日）
  const firstDayOfWeek = new Date(now.getTime() - currentDay * 86400000); // 当前日期减去当前是周几乘以一天的毫秒数，得到本周第一天的日期
  const lastDayOfWeek = new Date(firstDayOfWeek.getTime() + 6 * 86400000); // 本周第一天的日期加上6天的毫秒数，得到本周最后一天的日期

  // 格式化日期为年-月-日的字符串形式
  const startDate = formatDate(firstDayOfWeek);
  const endDate = formatDate(lastDayOfWeek);

  return {
    startDate,
    endDate,
  }; // 返回开始时间和结束时间
};

// console.log(getThisWeekDates()); // 输出本周的开始时间和结束时间

export const getYesterdayDate = () => {
  const today = new Date();
  const yesterday = new Date(today);
  yesterday.setDate(yesterday.getDate() - 1);
  return formatDate(yesterday);
};

// const yesterday = getYesterdayDate();
// console.log(yesterday.toISOString().split('T')[0]); // 输出格式为YYYY-MM-DD

export const handleLoopCallBack = (callback) => {
  // #ifdef H5
  if (getEnv() == "WX_PUBLIC") {
    let num = 0;
    let timers = setInterval(() => {
      if (num == 5) {
        clearInterval(timers);
      }
      if (uni.getStorageSync("token")) {
        clearInterval(timers);
        callback();
      } else {
        num += 1;
        console.log(num);
      }
    }, 500);
  }
  // #endif
  // #ifdef MP-WEIXIN
  let num = 0;
  let timers = setInterval(() => {
    if (num == 5) {
      clearInterval(timers);
    }
    if (uni.getStorageSync("token")) {
      clearInterval(timers);
      callback();
    } else {
      num += 1;
      console.log(num);
    }
  }, 500);
  // #endif
};
